<template>
    <div class="table-wrapper">
        <h4>砌体非抗震设计的抗剪强度设计值</h4>
        <div class="buttonGroup">
            <el-button type="primary" @click="handleEditBrickTableHeader">
                {{ isEditTableHeader ? '保存表头' : '修改表头' }}
            </el-button>
            <el-button type="primary" @click="handleBrickBatchDelete">删除</el-button>
            <!-- <el-button type="primary" @click="handleBrickApply">应用</el-button> -->
        </div>
        <div class="table-content">
            <div class="table-left">
                <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange"
                    :row-class-name="tableRowClassName">
                    <el-table-column type="selection" />
                    <el-table-column type="index" label="序号" width="80" />
                    <el-table-column prop="ccsvType" header-align="center" label="砌体类别" width="480">
                        <template #default="scope">
                            <span v-if="!scope.row.isEdit">{{ scope.row.ccsvType }}</span>
                            <el-input v-else v-model="scope.row.ccsvType" size="small"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column header-align="center" label="砂浆强度等级">
                        <template v-if="tableColumns && tableColumns.length > 0">
                            <el-table-column v-for="(item, index) in tableColumns" :key="index" :prop="item.filedProp"
                                :label="item.filedName" header-align="center" align="center"
                                :class-name="item.defaultData == '1' ? 'add-column' : ''">
                                <template #header>
                                    <!-- 新增列复选框形式 -->
                                    <el-checkbox v-if="item.defaultData == '1'" v-model="item.checked">&nbsp;</el-checkbox>
                                    <!-- 基础列形式 -->
                                    <el-input v-if='isEditTableHeader' v-model="item.filedName" size="small" placeholder="输入表头" style="width: 70%;" />
                                    <span v-else>{{ item.filedName }}</span>
                                </template>
                                <template #default="scope">
                                    <span v-if="!scope.row.isEdit">{{ scope.row[item.filedProp] }}</span>
                                    <el-input v-else v-model="scope.row[item.filedProp]" size="small"></el-input>
                                </template>
                            </el-table-column>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" fixed="right" width="120">
                        <template #default="scope">
                            <el-button type="text" size="small" @click="handleBrickModify(scope.$index, scope.row)">
                                {{ scope.row.isEdit ? '应用' : '修改' }}
                            </el-button>
                            <el-button type="text" size="small"
                                @click="handleBrickDelete(scope.$index, scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-button class="add" style="width: 100%" @click="handleBrickAdd()">
                    <el-icon style="vertical-align: middle">
                        <Plus />
                    </el-icon>
                </el-button>
            </div>
            <div class="table-right">
                <el-button class="add" @click="handleBrickColumnAdd()">
                    <el-icon style="vertical-align: middle">
                        <Plus />
                    </el-icon>
                </el-button>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
// 获取当前实例
const { proxy } = getCurrentInstance();
// 引入接口
import { getAllCsValue, saveOrUpdateCsValue, deleteCsValueById } from "@/api/vulnerModelManagement/reinforcedConcrete.js";
// 是否修改表头
const isEditTableHeader = ref(false);
const multipleSelection = ref([]);
const tableData = ref([]);
const tableColumns = ref([]);

//修改表头
const handleEditBrickTableHeader = () => {
    if (isEditTableHeader.value) { // 修改表头
        const paramsp = {
            csValueList: [],
            dynamicFieldsList: []
        }
        let flag = tableColumns.value.every(item=>(item.filedName&&item.filedName!=''))
		if(!flag){
			proxy.$modal.msgWarning('表头名称不能为空！')
			return;
		}
        tableColumns.value.forEach(item => {
            paramsp.dynamicFieldsList.push({
                cbrsId: item.cbrsId, //id
                cbrsKey: item.cbrsKey, //表名
                cbrsColumn: item.cbrsColumn, //列
                info: item.filedName, //字段名称
            })
        })
        saveOrUpdateCsValue(paramsp).then((res) => {
            if (res.code === 200) {
                ElMessage({
                    type: 'success',
                    message: '添加成功!'
                });
                isEditTableHeader.value = false
            }
        }).catch(err => {
            console.log(err);
        });
    } else {
        isEditTableHeader.value = true
    }
}
//修改 保存
const handleBrickModify = (index, row) => {
    if (row.isEdit) { // 编辑状态点击时，代表保存
        let isValid = true; // 用于标记所有输入是否有效
        for (const key in row) {
            if (Object.hasOwnProperty.call(row, key)) {
                if (key !== 'isEdit' && key !== 'isNew') {
                    const element = row[key];
                    if (element === '' || element === null) {
                        ElMessage({
                            type: 'warning',
                            message: '请填写数据!'
                        });
                        isValid = false;
                        break; // 一旦发现无效数据，立即退出循环
                    }
                }
            }
        }
        if (isValid) {
        onAddOrUpdateRows(row)
        }
        // onSearch()
    } else {
        row.isEdit = true
    }
}
// 表格选择事件
const handleSelectionChange = (val) => {
    multipleSelection.value = val
}
// 表格行状态
const tableRowClassName = ({ row, rowIndex }) => {
    if (row.defaultData == '1') {
        return 'add-row';
    } else {
        return '';
    }
}
//删除单行
const handleBrickDelete = (index, row) => {
    //删除
    ElMessageBox.confirm('确认删除数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        if (row.ccsvId) {
            await onDeleteRows(row.ccsvId.join(','), '')
        } else {
            tableData.value.splice(index, 1)
        }
        onSearch()
    }).catch((error) => {
        console.error(error)
        ElMessage({
            type: 'info',
            message: '已取消删除'
        });
    });
}
//删除多行
const handleBrickBatchDelete = () => {
    //删除
    ElMessageBox.confirm('确认删除数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        //multipleSelection.value[0].ccsvId.join(',')
        let ids = []
        multipleSelection.value.forEach(item => { ids = ids.concat(item.ccsvId) })
        const arrangeIds = []
        tableColumns.value.forEach(item => {
            if (item.defaultData === "1" && item.checked) {
                arrangeIds.push(item.cbrsId)
            }
        })
        await onDeleteRows(ids.join(','), arrangeIds.join(','))
        onSearch()
    }).catch((error) => {
        console.error(error)
        ElMessage({
            type: 'info',
            message: '已取消删除'
        });
    });
}
//新增行事件
const handleBrickAdd = async () => {
    const newObj = { ccsvType: '', isEdit: true, isNew: true }
    tableColumns.value.forEach(item => {
        newObj[item.filedProp] = ''
    })
    tableData.value.push(newObj)
}
//新增列事件
const handleBrickColumnAdd = async () => {
    await onAddColumn()
    //onSearch()
}
//查询
const onSearch = () => {
    const paramsp = { titleName: '砌体非抗震设计的抗剪强度设计值' }
    // 砌体非抗震设计的抗剪强度设计值表查询
    getAllCsValue(paramsp).then((res) => {
        if (res.code === 200) {
            console.log(res)
            buildTableColum(res.data.dynamicFieldsList)
            buildTableData(res.data.csValueList)
        }
    }).catch(err => {
        console.log(err);
    });
}
// 构建砌体非抗震设计的抗剪强度设计值表格的动态列结构
const buildTableColum = (dynamicFieldsList) => {
    tableColumns.value = [];
    dynamicFieldsList.forEach(item => {
        const cloumn = {
            filedName: item.info,
            filedProp: 'dynamicField-' + item.cbrsColumn,
            cbrsColumn: item.cbrsColumn,
            cbrsId: item.cbrsId,
            cbrsKey: item.cbrsKey,
            checked: false,
            defaultData: item.defaultData
        }
        tableColumns.value.push(cloumn)
    })
}
// 构建砌体非抗震设计的抗剪强度设计值表格的数据
const buildTableData = (csValueList) => {
    tableData.value = [];
    //循环遍历之前加上非空判断
    if (csValueList && csValueList.length >= 0) {
        csValueList.forEach((item) => {
            // 判断表格中是否已经有该条件
            const found = tableData.value.find(element => element.ccsvType === item.ccsvType);
            // 已经存在该条件
            if (found) {
                const findConlum = tableColumns.value.find(col => col.cbrsId === item.projectId)
                if (findConlum) {
                    found[findConlum.filedProp] = item.strengthValue
                }
                //found['dynamicField-' + item.ccsvColumn] = item.strengthValue
                found.ccsvId.push(item.ccsvId)
                found.origin.push(item)
            } else {  // 不存在
                const data = {
                    isEdit: false,
                    ccsvType: item.ccsvType,
                    defaultData: item.defaultData,
                    ccsvId: [],
                    origin: []
                }
                //data['dynamicField-' + item.ccsvColumn] = item.strengthValue
                const findConlum = tableColumns.value.find(col => col.cbrsId === item.projectId)
                if (findConlum) {
                    data[findConlum.filedProp] = item.strengthValue
                }
                data.ccsvId.push(item.ccsvId)
                data.origin.push(item)
                tableData.value.push(data);
            }
        });
    }
}
//砌体非抗震设计的抗剪强度设计值添加  新增列
const onAddColumn = async () => {
    const cbrsColumns = tableColumns.value.map(item => item.cbrsColumn)
    let maxColumns = cbrsColumns.reduce((a, b) => Math.max(a, b), -Infinity);
    if (!maxColumns) {
        maxColumns = 0
    }
    ElMessageBox.confirm('确认新增列, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        const ccsvColumn = maxColumns + 1
        const paramsp = {
            "csValueList": [
                // {
                //     "ccsvType": "现浇钢筋混凝土构件沿高度断面无突变",
                //     "ccsvColumn": ccsvColumn,
                //     "strengthValue": ""
                // },
            ],
            "dynamicFieldsList": [
                {
                    "cbrsColumn": ccsvColumn,
                    "cbrsKey": "砌体非抗震设计的抗剪强度设计值",
                    "info": '新增列'
                }
            ]
        }
        await saveOrUpdateCsValue(paramsp).then((res) => {
            if (res.code === 200) {
                ElMessage({
                    type: 'success',
                    message: '添加成功!'
                });
                onSearch()
            }
        }).catch(err => {
            console.log(err);
            ElMessage({
                type: 'info',
                message: '添加失败'
            });
        });
    }).catch(err => {
        ElMessage({
            type: 'info',
            message: '已取消新增'
        });
    });
}

//砌体非抗震设计的抗剪强度设计值添加行  新增行或更新保存行，存在同名ccsvType是更新，不存在是添加
const onAddOrUpdateRows = async (row) => {
    const csValueList = []
    if (row.origin?.length > 0) {
        // row.origin.forEach(item => {
        //     csValueList.push({
        //         ccsvId: item.ccsvId,
        //         ccsvType: row.ccsvType,
        //         ccsvColumn: item.ccsvColumn,
        //         strengthValue: row['dynamicField-' + item.ccsvColumn],
        //     })
        // })
        tableColumns.value.forEach(col => {
            const findOrigin = row.origin.find(item => col.cbrsId === item.projectId)
            if (findOrigin) {
                csValueList.push({
                    ccsvId: findOrigin.ccsvId,
                    ccsvType: row.ccsvType,
                    // cbrmColumn: findOrigin.cbrmColumn,
                    strengthValue: row[col.filedProp],
                    projectId: col.cbrsId
                })
            } else {
                csValueList.push({
                    // cbrmId: item.cbrmId,
                    ccsvType: row.ccsvType,
                    // cbrmColumn: item.cbrmColumn,
                    strengthValue: row[col.filedProp],
                    projectId: col.cbrsId
                })
            }
        })
    } else {
        tableColumns.value.forEach(item => {
            csValueList.push({
                ccsvType: row.ccsvType,
                ccsvColumn: item.cbrsColumn,
                strengthValue: row['dynamicField-' + item.cbrsColumn],
                projectId: item.cbrsId
            })
        })
    }
    let flag = csValueList.every(item => {
        return  item.strengthValue==='-'||(/^\d+(\.\d+)?$/.test(item.strengthValue) && parseFloat(item.strengthValue) >= 0);
    });
    if (!flag) {
        proxy.$modal.msgWarning('请输入正确的系数值！');
        return;
    }
    const paramsp = {
        csValueList
    }
    await saveOrUpdateCsValue(paramsp).then((res) => {
        if (res.code === 200) {
            row.isEdit = false
            row.isNew = false
            ElMessage({
                type: 'success',
                message: '保存成功!'
            });
        }
    }).catch(err => {
        console.log(err);
    });
    onSearch()
}

// 删除行
const onDeleteRows = async (ids, arrangeIds) => {
    if ((!ids || ids.length <= 0) && (!arrangeIds || arrangeIds.length <= 0)) {
        ElMessage({
            type: 'warning',
            message: '请选中数据!'
        });
        return
    }
    const paramsp = { csValueIds: ids, arrangeIds: arrangeIds }
    await deleteCsValueById(paramsp).then((res) => {
        if (res.code === 200) {
            ElMessage({
                type: 'success',
                message: '删除成功!'
            });
        }

    }).catch(err => {
        ElMessage({
            type: 'error',
            message: '删除失败!'
        });
    })
}

// 挂载
onMounted(() => {
    onSearch()
});
</script>

<style lang="scss" scoped></style>